package com.muyu.payment.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.muyu.common.core.utils.IdGenerator;
import com.muyu.payment.domain.WithdrawOrder;
import com.muyu.payment.domain.req.WithdrawReq;
import com.muyu.payment.mapper.WithdrawOrderMapper;
import com.muyu.payment.service.UserBalanceService;
import com.muyu.payment.service.WithdrawService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 提现服务实现类
 *
 * @author muyu
 * @date 2025-01-27
 */
@Slf4j
@Service
public class WithdrawServiceImpl extends ServiceImpl<WithdrawOrderMapper, WithdrawOrder> implements WithdrawService {

    @Autowired
    private WithdrawOrderMapper withdrawOrderMapper;

    @Autowired
    private UserBalanceService userBalanceService;

    // 提现手续费率（示例：0.1%）
    private static final BigDecimal WITHDRAW_FEE_RATE = new BigDecimal("0.001");
    // 最小提现金额
    private static final BigDecimal MIN_WITHDRAW_AMOUNT = new BigDecimal("1.00");
    // 最大提现金额
    private static final BigDecimal MAX_WITHDRAW_AMOUNT = new BigDecimal("50000.00");

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WithdrawOrder createWithdrawOrder(Long userId, String userName, WithdrawReq request) {
        try {
            // 参数验证
            if (request.getAmount().compareTo(MIN_WITHDRAW_AMOUNT) < 0) {
                throw new RuntimeException("提现金额不能小于" + MIN_WITHDRAW_AMOUNT + "元");
            }
            if (request.getAmount().compareTo(MAX_WITHDRAW_AMOUNT) > 0) {
                throw new RuntimeException("提现金额不能大于" + MAX_WITHDRAW_AMOUNT + "元");
            }

            // 检查用户余额是否充足
            if (!userBalanceService.checkBalanceSufficient(userId, request.getAmount())) {
                throw new RuntimeException("用户余额不足");
            }

            // 计算手续费
            BigDecimal fee = request.getAmount().multiply(WITHDRAW_FEE_RATE);
            BigDecimal actualAmount = request.getAmount().subtract(fee);

            // 生成订单号
            String orderNo = "WD" +IdGenerator.generateId();

            // 创建提现订单
            WithdrawOrder withdrawOrder = WithdrawOrder.builder()
                    .orderNo(orderNo)
                    .userId(userId)
                    .userName(userName)
                    .amount(request.getAmount())
                    .fee(fee)
                    .actualAmount(actualAmount)
                    .payType(request.getPayType())
                    .receiveAccount(request.getReceiveAccount())
                    .receiveName(request.getReceiveName())
                    .orderStatus(0) // 待审核
                    .remark(request.getRemark())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build();

            save(withdrawOrder);

//            // 冻结用户余额
//            boolean freezeSuccess = userBalanceService.freezeBalance(
//                    userId,
//                    request.getAmount(),
//                    orderNo,
//                    "提现申请冻结"
//            );
//
//            if (!freezeSuccess) {
//                throw new RuntimeException("冻结用户余额失败");
//            }

            log.info("创建提现订单成功，订单号: {}, 用户ID: {}, 金额: {}", orderNo, userId, request.getAmount());
            return withdrawOrder;
        } catch (Exception e) {
            log.error("创建提现订单失败，用户ID: {}, 金额: {}", userId, request.getAmount(), e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean auditWithdrawOrder(String orderNo, Integer auditResult, String auditor, String auditRemark) {
        try {
            WithdrawOrder withdrawOrder = getWithdrawOrderByOrderNo(orderNo);
            if (withdrawOrder == null) {
                log.error("提现订单不存在，订单号: {}", orderNo);
                return false;
            }

            // 检查订单状态
            if (withdrawOrder.getOrderStatus() != 0) {
                log.warn("提现订单状态异常，无法审核，订单号: {}, 当前状态: {}", orderNo, withdrawOrder.getOrderStatus());
                return false;
            }

            // 更新订单状态
            withdrawOrder.setOrderStatus(auditResult);
            withdrawOrder.setAuditor(auditor);
            withdrawOrder.setAuditRemark(auditRemark);
            withdrawOrder.setAuditTime(new Date());
            withdrawOrder.setUpdateTime(new Date());

            // 如果审核拒绝，解冻用户余额
//            if (auditResult == 2) {
//                boolean unfreezeSuccess = userBalanceService.unfreezeBalance(
//                        withdrawOrder.getUserId(),
//                        withdrawOrder.getAmount(),
//                        orderNo,
//                        "提现审核拒绝，解冻余额"
//                );
//
//                if (!unfreezeSuccess) {
//                    log.error("解冻用户余额失败，订单号: {}", orderNo);
//                    return false;
//                }
//            }

            updateById(withdrawOrder);

            log.info("审核提现订单成功，订单号: {}, 审核结果: {}", orderNo, auditResult);
            return true;
        } catch (Exception e) {
            log.error("审核提现订单失败，订单号: {}", orderNo, e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean processWithdrawOrder(String orderNo, Integer status, String thirdPartyTradeNo, String failReason) {
        try {
            WithdrawOrder withdrawOrder = getWithdrawOrderByOrderNo(orderNo);
            if (withdrawOrder == null) {
                log.error("提现订单不存在，订单号: {}", orderNo);
                return false;
            }

            // 检查订单状态
            if (withdrawOrder.getOrderStatus() != 1) {
                log.warn("提现订单状态异常，无法处理，订单号: {}, 当前状态: {}", orderNo, withdrawOrder.getOrderStatus());
                return false;
            }

            // 更新订单状态
            withdrawOrder.setOrderStatus(status);
            withdrawOrder.setThirdPartyTradeNo(thirdPartyTradeNo);
            withdrawOrder.setProcessTime(new Date());
            withdrawOrder.setUpdateTime(new Date());

            if (status == 3) { // 提现成功
                // 减少用户余额（从冻结余额中扣除）
                boolean success = userBalanceService.decreaseBalance(
                        withdrawOrder.getUserId(),
                        withdrawOrder.getAmount(),
                        2, // 提现
                        orderNo,
                        "提现成功"
                );

                if (!success) {
                    log.error("减少用户余额失败，订单号: {}", orderNo);
                    return false;
                }
            } else if (status == 4) { // 提现失败
                withdrawOrder.setFailReason(failReason);
                
//                // 解冻用户余额
//                boolean unfreezeSuccess = userBalanceService.unfreezeBalance(
//                        withdrawOrder.getUserId(),
//                        withdrawOrder.getAmount(),
//                        orderNo,
//                        "提现失败，解冻余额"
//                );
//
//                if (!unfreezeSuccess) {
//                    log.error("解冻用户余额失败，订单号: {}", orderNo);
//                    return false;
//                }
            }

            updateById(withdrawOrder);

            log.info("处理提现订单成功，订单号: {}, 状态: {}", orderNo, status);
            return true;
        } catch (Exception e) {
            log.error("处理提现订单失败，订单号: {}", orderNo, e);
            throw e;
        }
    }

    @Override
    public WithdrawOrder getWithdrawOrderByOrderNo(String orderNo) {
        return withdrawOrderMapper.selectByOrderNo(orderNo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelWithdrawOrder(String orderNo) {
        try {
            WithdrawOrder withdrawOrder = getWithdrawOrderByOrderNo(orderNo);
            if (withdrawOrder == null) {
                log.error("提现订单不存在，订单号: {}", orderNo);
                return false;
            }

            // 只有待审核状态的订单才能取消
            if (withdrawOrder.getOrderStatus() != 0) {
                log.warn("提现订单状态异常，无法取消，订单号: {}, 当前状态: {}", orderNo, withdrawOrder.getOrderStatus());
                return false;
            }

            // 更新订单状态为已取消
            withdrawOrder.setOrderStatus(5);
            withdrawOrder.setUpdateTime(new Date());
            updateById(withdrawOrder);

//            // 解冻用户余额
//            boolean unfreezeSuccess = userBalanceService.unfreezeBalance(
//                    withdrawOrder.getUserId(),
//                    withdrawOrder.getAmount(),
//                    orderNo,
//                    "用户取消提现，解冻余额"
//            );
//
//            if (!unfreezeSuccess) {
//                log.error("解冻用户余额失败，订单号: {}", orderNo);
//                return false;
//            }

            log.info("取消提现订单成功，订单号: {}", orderNo);
            return true;
        } catch (Exception e) {
            log.error("取消提现订单失败，订单号: {}", orderNo, e);
            throw e;
        }
    }
}